﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DevExpress.Web.ASPxCallback;
using System.Web.Security;
using TireService.Data;

namespace TireService.Website
{
    public partial class Glemt : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// Callback function that reset user password and send email to user/customer
        /// </summary>
        protected void callBackResetPassword_Callback(object sender, CallbackEventArgs e)
        {
            try
            {
                // Get email
                string email = e.Parameter;

                // Get user
                MembershipUser user = Membership.GetUser(email);

                // Validate user
                if (user == null)
                {
                    throw new ArgumentException("Bruger blev ikke fundet - kontakt venligst vores kunde support");
                }
                else
                {
                    // Unlock user, if locked out
                    if (user.IsLockedOut)
                    {
                        user.UnlockUser();
                    }

                    // Instantiate data layer
                    TireServiceDB db = new TireServiceDB();

                    // Get customer
                    Customer customer = db.GetCustomer(new Guid(user.ProviderUserKey.ToString()));

                    if (customer != null)
                    {
                        // Create new random password
                        string oldpassword = user.ResetPassword();
                        string newpassword = customer.Phone1.ToString();

                        // Set new password equal customer phone
                        user.ChangePassword(oldpassword, newpassword);

                        EmailNotificationServices emailService = new EmailNotificationServices();
                        emailService.Customer_UserInformation_SendCustomerEmail(user.Email, customer.Name, user.UserName, newpassword, customer.CustomerId);
                    }
                    else
                    {
                        throw new ArgumentException("Bruger ikke fundet");
                    }
                }

                e.Result = "1";
            }
            catch (Exception ex)
            {
                // Error
                e.Result = "0" + "|" + ex.Message;

            }
        }
    }
}